/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Enum.SearchGeneralEnum;
import dao.ChiTietHoaDonDAO;
import dao.ChiTietPhieuThuDAO;
import dao.NguoiDungDAO;
import dao.PhieuThuDAO;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import pojo.ChiTietHoaDon;
import pojo.ChiTietPhieuThu;
import pojo.NguoiDung;
import pojo.PhieuThu;

/**
 *
 * @author softviet
 */
public class PhieuThuGUI extends javax.swing.JDialog {

    /**
     * Creates new form PhieuThuGUI
     */
    private static Logger logger = Logger.getLogger(PhieuThuGUI.class);
    private PhieuThu phieuThu;
    private ArrayList<ChiTietPhieuThu> chiTietPhieuThus;
    private ArrayList<ChiTietHoaDon> chiTietHoaDons;
    private JErrorProvider errorProvider;
    private NguoiDung selectedKhachHang;
    private MyEventListener ButtonLuuClickedListener;

    public PhieuThuGUI(java.awt.Frame parent, boolean modal, PhieuThu phieuThu) {
        super(parent, modal);
        initComponents();
        errorProvider = new JErrorProvider();
        this.phieuThu = phieuThu;
        SetTabOrder();
        if (phieuThu.getId() == 0) {
            this.setTitle("Lập phiếu thu");
        } else {
            this.setTitle("Chi tiết phiếu thu");
            txtMaKhachHang.setEditable(false);
            dtNgayLapPhieu.setEditable(false);
            btnSearchMaKhachHang.setEnabled(false);
            btnClear.setEnabled(false);
            btnLuu.setEnabled(false);
            btnXoa.setEnabled(false);
            btnXuly.setEnabled(false);
        }
        FormatControls();
        AutoLoad();
    }

    private void SetTabOrder() {
        IndexedFocusTraversalPolicy indexedFocusTraversalPolicy = new IndexedFocusTraversalPolicy();
        indexedFocusTraversalPolicy.addIndexedComponents(new Component[]{txtMaKhachHang, btnSearchMaKhachHang, txtTenKhachHang, dtNgayLapPhieu, txtTongTienThu, btnXuly, btnXoa, btnClear, btnLuu, btnThoat});
        setFocusTraversalPolicy(indexedFocusTraversalPolicy);
    }

    private void FormatControls() {
        Utility.FormatNumberStringTextfield(txtMaKhachHang);
        Utility.FormatDecimalTextfield(txtTongTienThu);
    }

    private void AutoLoad() {
        if (phieuThu.getNgayLapPhieu() == null) {
            dtNgayLapPhieu.setDate(new Date());
        }
        chiTietHoaDons = new ArrayList<>();
        if(phieuThu.getId()!=0){
            try {
                setSelectedKhachHang(phieuThu.getNguoiDung());
                dtNgayLapPhieu.setDate(phieuThu.getNgayLapPhieu());
                txtTongTienThu.setValue(phieuThu.getTongTienThu());
                chiTietPhieuThus=(ArrayList<ChiTietPhieuThu>) ChiTietPhieuThuDAO.LayDanhSachPhieuThuByPhieuThuID(phieuThu.getId());
                for(ChiTietPhieuThu chiTietPhieuThu:chiTietPhieuThus){
                    chiTietHoaDons.add(chiTietPhieuThu.getChiTietHoaDon());
                }
            } catch (Exception ex) {
                logger.error(new Date().toString(), ex);
                JOptionPane.showMessageDialog(this, ex.getMessage());
            }
        }
        Utility.CreateColumnsFromDB(ChiTietHoaDon.class, chiTietHoaDons, tbChiTietPhieuThu, new String[]{"Tên sản phẩm", "Đơn giá", "Số lượng", "Tổng tiền", "Mã hoá đơn"}, new String[]{"id", "maSanPhamCuaHang", "daThanhToan"});
    }

    private int CheckDataBeforeXuLy() {
        int dem = 0;
        errorProvider.clear();
        if (txtMaKhachHang.getText().isEmpty()) {
            errorProvider.setError(txtMaKhachHang, "required");
            dem++;
        }
        return dem;
    }
    
    private void CalculateTongTienThu(){
        Double tongTienThu=0.0;
        for(ChiTietHoaDon chiTietHoaDon:chiTietHoaDons){
            tongTienThu+=chiTietHoaDon.getTongTien();
        }
        txtTongTienThu.setValue(tongTienThu==0?null:tongTienThu);
    }
    
    private int CheckDataBeforeLuu(){
        int dem=0;
        errorProvider.clear();
        if(txtMaKhachHang.getText().isEmpty()){
            errorProvider.setError(txtMaKhachHang, "required");
            dem++;
        }
        if(dtNgayLapPhieu.getDate()==null){
            errorProvider.setError(dtNgayLapPhieu, "required");
            dem++;
        }
        if(dem==0 && chiTietHoaDons.isEmpty()){
            JOptionPane.showMessageDialog(this, "Không có phí để thu nên không thể lập phiếu thu");
            dem++;
        }
        return dem;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtMaKhachHang = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtTenKhachHang = new javax.swing.JTextField();
        btnSearchMaKhachHang = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        dtNgayLapPhieu = new org.jdesktop.swingx.JXDatePicker();
        jLabel4 = new javax.swing.JLabel();
        txtTongTienThu = new javax.swing.JFormattedTextField();
        btnXuly = new javax.swing.JButton();
        btnXoa = new javax.swing.JButton();
        btnClear = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbChiTietPhieuThu = new org.jdesktop.swingx.JXTable();
        btnLuu = new javax.swing.JButton();
        btnThoat = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Phiếu thu");
        setResizable(false);

        jLabel1.setText("Mã khách hàng");

        txtMaKhachHang.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtMaKhachHangFocusLost(evt);
            }
        });

        jLabel2.setText("Tên khách hàng");

        txtTenKhachHang.setEditable(false);

        btnSearchMaKhachHang.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/SearchIconImage.gif"))); // NOI18N
        btnSearchMaKhachHang.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchMaKhachHangActionPerformed(evt);
            }
        });

        jLabel3.setText("Ngày lập phiếu");

        jLabel4.setText("Tổng tiền thu");

        txtTongTienThu.setEditable(false);

        btnXuly.setText("Xử lý");
        btnXuly.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnXulyActionPerformed(evt);
            }
        });

        btnXoa.setText("Xoá");
        btnXoa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnXoaActionPerformed(evt);
            }
        });

        btnClear.setText("Clear");
        btnClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnClearActionPerformed(evt);
            }
        });

        tbChiTietPhieuThu.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(tbChiTietPhieuThu);

        btnLuu.setText("Lưu");
        btnLuu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLuuActionPerformed(evt);
            }
        });

        btnThoat.setText("Thoát");
        btnThoat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnThoatActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnLuu)
                .addGap(18, 18, 18)
                .addComponent(btnThoat)
                .addGap(271, 271, 271))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtTenKhachHang, javax.swing.GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE)
                            .addComponent(txtMaKhachHang))
                        .addGap(26, 26, 26)
                        .addComponent(btnSearchMaKhachHang, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(56, 56, 56)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtTongTienThu)
                            .addComponent(dtNgayLapPhieu, javax.swing.GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(243, 243, 243)
                        .addComponent(btnXuly)
                        .addGap(18, 18, 18)
                        .addComponent(btnXoa)
                        .addGap(18, 18, 18)
                        .addComponent(btnClear)))
                .addContainerGap(31, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnSearchMaKhachHang, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(dtNgayLapPhieu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(txtMaKhachHang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtTenKhachHang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(txtTongTienThu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnXuly)
                    .addComponent(btnXoa)
                    .addComponent(btnClear))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnLuu)
                    .addComponent(btnThoat))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnThoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThoatActionPerformed
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_btnThoatActionPerformed

    private void btnSearchMaKhachHangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchMaKhachHangActionPerformed
        // TODO add your handling code here:
        try {
            // TODO add your handling code here:
            DialogGeneralSeach dialogGeneralSeach = new DialogGeneralSeach(null, true, SearchGeneralEnum.KhachHang);
            final int x = (getWidth() - dialogGeneralSeach.getWidth()) + getX() / 2;
            final int y = (getHeight() - dialogGeneralSeach.getHeight()) + getY();
            dialogGeneralSeach.setLocation(x, y);
            dialogGeneralSeach.setButtonOKClickedListenner(new MyEventListener() {
                @Override
                public void myEventOccured(Object evt) {
                    setSelectedKhachHang((NguoiDung) evt);
                }
            });
            dialogGeneralSeach.setVisible(true);
        } catch (Exception ex) {
            logger.error(new Date().toString(), ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_btnSearchMaKhachHangActionPerformed

    private void txtMaKhachHangFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMaKhachHangFocusLost
        // TODO add your handling code here:
        try {
            if (!txtMaKhachHang.getText().isEmpty()) {
                if (selectedKhachHang == null || Integer.parseInt(txtMaKhachHang.getText()) != selectedKhachHang.getId()) {
                    NguoiDung nguoiDung = (NguoiDung) NguoiDungDAO.LayTheoID(NguoiDung.class, Integer.parseInt(txtMaKhachHang.getText()));
                    if (nguoiDung == null) {
                        JOptionPane.showMessageDialog(this, "Không tìm thấy mã khách hàng này trong hệ thống");
                    }
                    setSelectedKhachHang(nguoiDung);
                }
            } else {
                setSelectedKhachHang(null);
            }
        } catch (Exception ex) {
            logger.error(new Date().toString(), ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_txtMaKhachHangFocusLost

    private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed
        // TODO add your handling code here:
        setSelectedKhachHang(null);
        dtNgayLapPhieu.setDate(new Date());
        txtTongTienThu.setValue(null);
    }//GEN-LAST:event_btnClearActionPerformed

    private void btnXulyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXulyActionPerformed
        try {
            // TODO add your handling code here:
            if (CheckDataBeforeXuLy() > 0) {
                return;
            }
            chiTietHoaDons = (ArrayList<ChiTietHoaDon>) ChiTietHoaDonDAO.LayDanhSachForLapPhieuThu(Integer.parseInt(txtMaKhachHang.getText()), MainGUI.nguoiDung);
            Utility.CreateColumnsFromDB(ChiTietHoaDon.class, chiTietHoaDons, tbChiTietPhieuThu, new String[]{"Tên sản phẩm", "Đơn giá", "Số lượng", "Tổng tiền", "Mã hoá đơn"}, new String[]{"id", "maSanPhamCuaHang", "daThanhToan"});
            CalculateTongTienThu();
            if (chiTietHoaDons.isEmpty()) {
                JOptionPane.showMessageDialog(this, "Không tìm thấy");
            }
        } catch (Exception ex) {
            logger.error(new Date().toString(), ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_btnXulyActionPerformed

    private void btnXoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXoaActionPerformed
        // TODO add your handling code here:
        List<ChiTietHoaDon> cthds=(List<ChiTietHoaDon>) Utility.GetSelectedRows(tbChiTietPhieuThu, chiTietHoaDons);
        if(!cthds.isEmpty()){
            if(JOptionPane.showConfirmDialog(this, "Bạn có chắc muốn xoá không?","Question",JOptionPane.YES_NO_OPTION)==0){
                Utility.RemoveSelectedRows(ChiTietHoaDon.class, tbChiTietPhieuThu, chiTietHoaDons, new String[]{"Tên sản phẩm", "Đơn giá", "Số lượng", "Tổng tiền", "Mã hoá đơn"}, new String[]{"id", "maSanPhamCuaHang", "daThanhToan"});
                CalculateTongTienThu();
            }
        }
        else{
            JOptionPane.showMessageDialog(this, "Xin chọn dữ liệu trên lưới để xoá");
        }
    }//GEN-LAST:event_btnXoaActionPerformed

    private void btnLuuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLuuActionPerformed
        try {
            // TODO add your handling code here:
            if(ButtonLuuClickedListener==null){
                return;
            }
            if(CheckDataBeforeLuu()>0){
                return;
            }
            phieuThu=new PhieuThu(0, MainGUI.nguoiDung.getCuaHang(), selectedKhachHang, dtNgayLapPhieu.getDate(), (Double)txtTongTienThu.getValue(), false, null);
            chiTietPhieuThus=new ArrayList<>();
            for(ChiTietHoaDon chiTietHoaDon:chiTietHoaDons){
                ChiTietPhieuThu chiTietPhieuThu=new ChiTietPhieuThu(0, chiTietHoaDon, phieuThu, false);
                chiTietPhieuThus.add(chiTietPhieuThu);
            }
            int id=PhieuThuDAO.Them(phieuThu, chiTietPhieuThus);
            phieuThu.setId(id);
            JOptionPane.showMessageDialog(this, "Lập phiếu thu thành công");
            ButtonLuuClickedListener.myEventOccured(phieuThu);
            dispose();
        } catch (Exception ex) {
            logger.error(new Date().toString(), ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_btnLuuActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClear;
    private javax.swing.JButton btnLuu;
    private javax.swing.JButton btnSearchMaKhachHang;
    private javax.swing.JButton btnThoat;
    private javax.swing.JButton btnXoa;
    private javax.swing.JButton btnXuly;
    private org.jdesktop.swingx.JXDatePicker dtNgayLapPhieu;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXTable tbChiTietPhieuThu;
    private javax.swing.JTextField txtMaKhachHang;
    private javax.swing.JTextField txtTenKhachHang;
    private javax.swing.JFormattedTextField txtTongTienThu;
    // End of variables declaration//GEN-END:variables

    /**
     * @param selectedKhachHang the selectedKhachHang to set
     */
    public void setSelectedKhachHang(NguoiDung selectedKhachHang) {
        this.selectedKhachHang = selectedKhachHang;
        if (selectedKhachHang != null) {
            txtMaKhachHang.setText(String.valueOf(selectedKhachHang.getId()));
            txtTenKhachHang.setText(selectedKhachHang.getTenNguoiDung());
        } else {
            txtMaKhachHang.setText(null);
            txtTenKhachHang.setText(null);
            txtTongTienThu.setValue(null);
        }
        chiTietHoaDons = new ArrayList<>();
        Utility.CreateColumnsFromDB(ChiTietHoaDon.class, chiTietHoaDons, tbChiTietPhieuThu, new String[]{"Tên sản phẩm", "Đơn giá", "Số lượng", "Tổng tiền", "Mã hoá đơn"}, new String[]{"id", "maSanPhamCuaHang", "daThanhToan"});
    }

    /**
     * @param ButtonLuuClickedListener the ButtonLuuClickedListener to set
     */
    public void setButtonLuuClickedListener(MyEventListener ButtonLuuClickedListener) {
        this.ButtonLuuClickedListener = ButtonLuuClickedListener;
    }
}
